import Schema from 'async-validator';
import rules from 'async-validator/lib/rule';
import { format, isEmptyValue } from 'async-validator/lib/util';
// 规则列表
import ruleDict from './rules';

/**
 *  @param rule 校验规则.
 *  @param value 源对象字段的值.
 *  @param callback 回调函数.
 *  @param source 校验后的源对象.
 *  @param options 校验选项.
 *  @param options.messages 校验信息.
 */
function validator(rule, value, callback, source, options) {
  const type = rule.type;
  const errors = [];
  // 如果表单值为空 且不是必填 不校验
  if (isEmptyValue(value, 'string') && !rule.required) {
    return callback();
  }
  // 校验必填
  rules.required(rule, value, source, errors, options);
  // 自定义规则校验
  if (!isEmptyValue(value, 'string') && !ruleDict[type](value)) {
    errors.push(format('%s 格式不正确', rule.fullField));
  }
  return callback(errors);
}

// 注册validator
Object.keys(ruleDict).forEach(key => {
  Schema.register(key, validator);
});

export default Schema;
